package cn.school.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
@WebFilter(filterName = "RoleFilter",value = "/*")
public class RoleFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了：RoleFilter");
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //>request.setCharacterEncoding("utf-8");
            String path = request.getServletPath();
            System.out.println("现在请求的地址是：" + path);
            if (path.endsWith(".gif") || path.equals("/loginServlet") || path.equals("/login.jsp")) {
                filterChain.doFilter(request, servletResponse);
                return;
            }
            Object user = request.getSession().getAttribute("USER");
            if (user == null) {
                request.setAttribute("errmsg", "您还没有登录，不能访问[" + path + "]");
                request.getRequestDispatcher("/login.jsp").forward(request, servletResponse);
                return;
            }
            //放行
            filterChain.doFilter(request, servletResponse);
        }finally {
            System.out.println("离开了：RoleFilter");
        }
    }

    @Override
    public void destroy() {

    }
}
